<?php

if(count($argv) <= 1)
{
    show_help();
    exit;
}

array_shift($argv);

switch($argv[0])
{
 case "controller":
    array_shift($argv);
    handle_controller($argv);
    break;
    
 case "model":
    array_shift($argv);
    handle_model($argv);
    break;
    
 default:
    show_help();
    break;
}

function handle_controller($args)
{
    if(empty($args[0]))
    {
	show_help();
	exit;
    }
    $controller = array_shift($args);
    if(file_exists("controllers/".$controller."_controller.php"))
    {
	echo "Controller already exists!\n";
	exit;
    }
    
    if(!$fp = fopen("controllers/".$controller."_controller.php", "w"))
    {
	echo "Cant open controllers/".$controller."_controller.php for writing!\n";
	exit;
    }
    $controller_name = ucfirst($controller)."Controller";
    $content = "<?php\n".
      "\n".
      "class $controller_name extends ApplicationController\n".
      "{\n".
      "    function __construct()\n".
      "    {\n".
      "        parent::__construct();\n".
      "    }\n".
      "\n";
    
    @mkdir("views/$controller");
    $args[] = "main";    
    foreach($args as $action)    
    {	
	$content .= "    function $action()\n".
	  "    { }\n";
	if($ap = fopen("views/$controller/$action.php", "w"))
	{
	    fwrite($ap, "<b>Find me in views/$controller/$action.php</b>\n");
	    fclose($ap);
	}
    }
    
    $content .= "}\n".
      "\n".
      "?>\n";
    
    fwrite($fp, $content);
    fclose($fp);
    echo "Controller $controller created!\n";
}

function handle_model($args)
{
    if(empty($args[0]))
    {
	show_help();
	exit;
    }
    $model = array_shift($args);
    if(file_exists("models/$model.php"))
    {
	echo "Model already exists!\n";
	exit;
    }
    
    if(!$fp = fopen("models/$model.php", "w"))
    {
	echo "Cant open models/$model.php for writing!\n";
	exit;
    }
    $model_name = ucfirst($model);
    $content = "<?php\n".
      "\n".
      "class $model_name extends ActiveRecord\n".
      "{\n".
      "    function __construct()\n".
      "    {\n".
      "        parent::__construct();\n".
      "    }\n".
      "}\n".
      "\n".
      "?>\n";
    
    fwrite($fp, $content);
    fclose($fp);    
}

function show_help()
{
    echo "Usage:\n".
      "php generate.php controller controller_name [action1 action2 ...]\n".
      "php generate.php model model_name\n";
}
?>
